package matching;

import java.util.ArrayList;

import parser.RTEXmlParser;

import data.RTEData;
import data.RTENode;
import data.RTEPreprocessedData;
import data.RTESentence;

public class LemmaMatch extends Matcher {
	
	public LemmaMatch(String task, double threshold) {
		super(task, threshold);
	}

	@Override
	public void match() {
		numberOfTextCases = RTEPreprocessedData.rtePreprocessedDataList.size();

		//iterate over all pairs
		for (RTEPreprocessedData rteData : RTEPreprocessedData.rtePreprocessedDataList) {
			int lemmaPosTagMatches = 0;
			int lemmaMatches = 0;
			int hypLength = 0;
			
			boolean entails = false;
			float idfValue = 0;
			float idfHypSum = 0;
			
			//Match all hyp sentences against all text sentences
			for (RTESentence hypSentence : rteData.getHypothesisSentences()) {
				ArrayList<RTENode> hypNodes = hypSentence.getNodes();
				hypLength += hypNodes.size();
				
				for (RTESentence textSentence : rteData.getTextSentences()) {
					ArrayList<RTENode> textNodes = textSentence.getNodes();
					
					for(int i = 0; i < textNodes.size(); i++) {
						RTENode t = textNodes.get(i);
						for(int j = 0; j < hypNodes.size(); j++) {
							RTENode h  = hypNodes.get(j);
							
							//check for lemma match
							if(t.getLemma().equals(h.getLemma()) && 
									   !t.getLemma().equals("")) {
										lemmaMatches++;
							}
							
							//check for lemma & pos tag match
							if(t.getLemma().equals(h.getLemma()) && 
							   !t.getLemma().equals("") &&
							   t.getPosTag().equals(h.getPosTag())
									) {
								lemmaPosTagMatches++;
								
								idfValue += idfPreProcessed.get(h.getLemma());
							}
						}
					}
				}
			}
			
			rteData.setLemmaMatchPercentage(lemmaMatches / (float)hypLength);
			rteData.setLemmaPosTagMatchPercentage(lemmaPosTagMatches / (float)hypLength);
			
			//calculate idfHypSum
			for(RTESentence sentence : rteData.getHypothesisSentences()) {
				for (RTENode node : sentence.getNodes()) {
					idfHypSum += idfPreProcessed.get(node.getLemma());
				}
			}
			
			//Calculate match percentage With IDF
			float idfWordMatch = idfValue / idfHypSum;
			if(idfWordMatch >= threshold) {
				entails = true;
			}else
				errors.add(rteData.getId());
						
			//Without IDF
			/*float matchPercentage = matches/(float)rteData.getHypothesis().size();
			if(matchPercentage >= threshold) { 
				entails = true;
			}		
			 */
			this.addJudgement(rteData.getId(), entails);
		
			if(entails == rteData.isEntailment()) { 
				entailments++;
			}			
		}
		correctness = (float)entailments/(float)numberOfTextCases;

		System.out.println(this);
		RTEXmlParser.WritePredictions("LemmaMatch", this.getJudgementData());
	}
}
